namespace Resharper.Abstractions.CodeDom.Statements.DoStatements
{
  using System;
  using JetBrains.Annotations;
  using JetBrains.ReSharper.Psi.CSharp.Tree;
  using Resharper.Abstractions.Actions;
  using Resharper.Abstractions.Shell;

  /// <summary>Defines the <see cref="DoStatementExtensions"/> class.</summary>
  public static class DoStatementExtensions
  {
    #region Public Methods

    /// <summary>Gets for statement.</summary>
    /// <param name="dataContext">The data context.</param>
    /// <returns>Returns the for statement.</returns>
    [CanBeNull]
    public static DoStatement GetDoStatement([NotNull] this DataContext dataContext)
    {
      if (dataContext == null)
      {
        throw new ArgumentNullException("dataContext");
      }

      var result = dataContext.GetSelectedElement<IDoStatement>();

      return result != null ? new DoStatement(result) : null;
    }

    /// <summary>Gets the selected literal expression.</summary>
    /// <param name="context">The context.</param>
    /// <returns>Returns the selected literal expression.</returns>
    [CanBeNull]
    public static DoStatement GetSelectedDoStatement([NotNull] this ProviderContext context)
    {
      if (context == null)
      {
        throw new ArgumentNullException("context");
      }

      var doStatement = context.InternalGetSelectedElement<IDoStatement>();
      if (doStatement == null)
      {
        return null;
      }

      var keyword = doStatement.DoKeyword;
      if (keyword == null)
      {
        return null;
      }

      var selectedTreeNode = context.GetSelectedTreeNode();
      if (selectedTreeNode == null)
      {
        return null;
      }

      if (!keyword.Contains(selectedTreeNode))
      {
        return null;
      }

      return new DoStatement(doStatement);
    }

    #endregion
  }
}